import java.util.Stack;

/**
 * Created by Administrator on 2016/9/20.
 */
public class Main_Baidu {
    public static void main(String[] args) {
        System.out.println(balancedParentheses("(()()))"));
    }
    public static int balancedParentheses(String str)
    {
        Stack<Character> stack = new Stack<>();
        if (str == null) return -1;
        int len = str.length();
        if (len < 2) return -1;
        int ans = 0;
        for (int i = 0; i < len; i++) {
            Character c = str.charAt(i);
            if (c.equals('(')) {
                stack.push('(');
            } else {
                if (stack.isEmpty()) {
                    return -1;
                } else {
                    ans++;
                    stack.pop();
                }
            }
        }
        if (!stack.isEmpty()) {
            return -1;
        }
        return ans;
    }
}
